#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/time.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <cstdio>
#include <cstring>
#include <fcntl.h>
#include <signal.h>
#include <pthread.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <vector>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <functional>
#include <semaphore.h>
#include <jsoncpp/json/json.h>
#include <sys/select.h>
#include "Log.hpp"
#include "TcpServer.hpp"
#define PORT 8081
#define FD_NONE -1
#define NUM 100
using namespace std;
class Poll
{
public:
    Poll(int port = PORT, int num = NUM)
        : _port(port), nfds(num)
    {
        tcpserver = new TcpServer(_port);
        _listensock = tcpserver->Sock();
        _pfds = new pollfd(nfds);
        _pfds[0] = _listensock;
        _pfds[0].events = POLLIN;
        for (int i = 1; i < nfds; i++)
        {
            _pfds[i].fd = FD_NONE;
            _pfds[i].events = _pfds[i].revents = 0;
        }
        poll(_pfds, nfds, 0);
    }
    void Accepter() // 默认服务端只能读
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof peer;
        int sock = accept(_listensock, (struct sockaddr *)&peer, &len);
        for (int i = 1; i < nfds; i++)
        {
            if (_pfds[i].fd == FD_NONE)
            {
                _pfds[i].fd = sock;
                _pfds[i].events = POLLIN;
                return;
            }
        }
        LOG(WARNING, "文件描述符已满");
    }
    void Recver(int pos)
    {
        char buffer[10240];
        int sock = _pfds[pos];
        int n = recv(sock, buffer, sizeof buffer);
        if (n > 0)
        {
            buffer[n] = 0;
            cout << buffer << endl;
        }
        else if (n == 0)
        {
            _pfds[pos].fd = FD_NONE;
            close(sock);
            LOG(INFO, "对端链接关闭");
            return;
        }
        else
        {
            _pfds[pos].fd = FD_NONE;
            close(sock);
            LOG(WARNING, "链接异常");
            return;
        }
    }
    void Loop()
    {
        while (1)
        {
            for (int i = 0; i < nfds; i++)
            {
                if (_pfds[i] != FD_NONE)
                {
                    if (_pfds[i].events & POLLIN)
                    {
                        if (_pfds[i] == _listensock)
                            Accepter();
                        else
                            Recver(i);
                    }
                }
            }
        }
    }

private:
    int _port;
    int _listensock;
    int nfds;
    struct pollfd *_pfds;
    TcpServer *tcpserver;
};